
#include <FS.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <time.h>

/*****************通用***********************/
const String DEFAULT_AP_SID = "ESP8266_Switch_AP";
const String DEFAULT_AP_PWD = "12345678";
const int BAUD_RATE = 9600;
const int AP_WEB_PORT = 80;
String AP_SID;
String AP_PWD;
long timezone = 2;
byte daysavetime = 1;
const char* CONFIG = "/config.json";

/*显示*/
void disTXT(String txt){
  Serial.println(txt);
}

void logger(String txt){
  Serial.println(txt);
}
/****************配置操作*********************/

bool getLocalTime(struct tm * info, uint32_t ms) {
  uint32_t count = ms / 10;
  time_t now;

  time(&now);
  localtime_r(&now, info);

  if (info->tm_year > (2016 - 1900)) {
    return true;
  }

  while (count--) {
    delay(10);
    time(&now);
    localtime_r(&now, info);
    if (info->tm_year > (2016 - 1900)) {
      return true;
    }
  }
  return false;
}

void mountFS(){
  if (!SPIFFS.begin()) {
     Serial.println("Failed to mount file system");
   }
}
//读取配置文件
String loadPorperty(String key){
  File file = SPIFFS.open(CONFIG, "w+");
  Serial.println(file.read());
  file.close();
  return "";
}

void savePorperty(String key,String val){
  //读取文本
  File rf = SPIFFS.open(CONFIG, "w+");
 
}
void listDir(const char * dirname) {
  Serial.printf("Listing directory: %s\n", dirname);

  Dir root = SPIFFS.openDir(dirname);

  while (root.next()) {
    File file = root.openFile("r");
    Serial.print("  FILE: ");
    Serial.print(root.fileName());
    Serial.print("  SIZE: ");
    Serial.print(file.size());
    time_t t = file.getLastWrite();
    struct tm * tmstruct = localtime(&t);
    file.close();
    Serial.printf("  LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, (tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour, tmstruct->tm_min, tmstruct->tm_sec);
  }
}
/*****************AP模式**********************/
/* 热点的账号与密码 */
ESP8266WebServer server(AP_WEB_PORT);


void setAP(){
  Serial.println("SET AP");
  WiFi.softAP(DEFAULT_AP_SID, DEFAULT_AP_PWD);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("network gate is :");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.on("/scan", scan);
  server.on("/conectionAP", conectionAP);
  server.begin();
}

void scan() {
  String html = String("<html><head>");
  html += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf8\" />";
  html += "</head><body>";
  int n = WiFi.scanNetworks();
  Serial.print("found networks :");
  Serial.print(n);
  
  if (n == 0) {
    html += "<H1>没网还玩屁啊！</H1>";
  }
  else
  {
    html += "<H1>扫描到";
    html += n;
    html += "个热点，请选择进行连接~</H1>";
    html += "<form action=\"/conectionAP\" method=\"post\" ><ul style=\"list-style:none\">";
    for (int i = 0; i < n; ++i)
    {
      html += "\r\n<li><label><input type='radio' name='ap' value=\"";
      html += WiFi.SSID(i);
      html += "\"/>";
      // Print SSID and RSSI for each network found
      html += i + 1;
      html += "：";
      html += WiFi.SSID(i);
      html += "&nbsp;(";
      html += WiFi.RSSI(i);
      html += "dBm)&nbsp;";
      html += "CH:";
      html += WiFi.channel(i);
      html += "&nbsp;";
      switch (WiFi.encryptionType(i)) {
        case 5: html += "WEP"; break;
        case 2: html += "WPA/PSK"; break;
        case 4: html += "WPA2/PSK"; break;
        case 7: html += "OPEN"; break;
        case 8: html += "WPA/WPA2/PSK"; break;
      }
      html += "</label></li>";
      delay(10);
    }
    html += "<li>请输入密钥：<input name=\"pwd\" type=\"password\" /></li>";
    html += "<li><input type=\"submit\" value=\"连接\"/></li>";
    html += "</ul></form>";
    html += "<a href='/scan'>重新扫描</a>";
    html += "</body></html>";
  }
  server.send(200, "text/html", html);
}

void conectionAP() {
  if (server.hasArg("ap") && server.hasArg("pwd"))
  {
    String ap = server.arg("arg");
    String pwd = server.arg("pwd");
    Serial.println("change mode,conection...");
    WiFi.mode(WIFI_STA);
    WiFi.begin(ap, pwd);
    // Wait for connection 60s
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    //超过60s链接失败处理

    savePorperty("sid",ap);
    savePorperty("pwd",pwd);
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ap);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    String html = String(server.arg("ap"));
    html += "：";
    html += server.arg("pwd");
    server.send(200, "text/html", html);
  }
}

void handleRoot() {
  Serial.println("request /");
  savePorperty("test","1233");
  Serial.println(loadPorperty("test"));
  savePorperty("keyss","sdf");
  Serial.println(loadPorperty("keyss"));
  
  server.send(200, "text/html", "<html><head></head><body><h1>You are connected</h1><a href='/scan'>扫描SSID</a></body>");
}



void setup() {
  Serial.begin(BAUD_RATE);
  Serial.println("start");
  configTime(3600 * timezone, daysavetime * 3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org");
  struct tm tmstruct ;
  delay(2000);
  tmstruct.tm_year = 0;
  getLocalTime(&tmstruct, 5000);
  mountFS();
  setAP();

}

void loop() {
  server.handleClient();

}
